package ch.bfh.mobicomp;

import java.util.LinkedList;
import java.util.List;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;

public class CompassEventListener implements SensorEventListener {
	private int lastSensorValue = 0;
	private int currentSensorValue = 0;
	private List<SensorListener> listener = new LinkedList<SensorListener>();
	private SensorManager manager = null;

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
	}

	public void addCompassActionListener(SensorListener listener) {
		this.listener.add(listener);

		refreshEventBinding();
	}

	public void removeCompassActionListener(SensorListener listener) {
		this.listener.remove(listener);

		refreshEventBinding();
	}

	private void refreshEventBinding() {
		if (listener.size() > 0) {
			Log.d("alarm", "register listener");
			manager.registerListener((SensorEventListener) this,
					manager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
					SensorManager.SENSOR_DELAY_NORMAL);
		}
		else {
			Log.d("alarm", "unregister listener");
			manager.unregisterListener(this);
		}
	}

	public CompassEventListener(SensorManager manager) {
		this.manager = manager;
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		Log.d("alarm", "sensor data changed");
		currentSensorValue = Math.round(event.values[0] / 10)
				^ Math.round(event.values[1] / 10)
				^ Math.round(event.values[2] / 10);

		if (lastSensorValue != 0 && currentSensorValue != lastSensorValue) {
			if (listener != null)
				for (SensorListener l : listener)
					l.onSensorChanged();
		}

		lastSensorValue = currentSensorValue;
	}
}
